package com.liruo.learn.spring.mvc.enumconverter;

import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author:liruo
 * @Date:2023-02-22-17:48:10
 * @Desc
 */
public class SourceToEnumGenericConverter implements ConditionalGenericConverter {
    @Override
    public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
        Class<?> sourceClazz = sourceType.getType();
        if(sourceClazz != String.class && sourceClazz != Integer.class){
            return false;
        }
        Class<?> targetClazz = targetType.getType();
        return SourceEnum.class.isAssignableFrom(targetClazz);
    }

    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        HashSet<ConvertiblePair> set = new HashSet<>();
        set.add(new ConvertiblePair(String.class, SourceEnum.class));
        set.add(new ConvertiblePair(Integer.class, SourceEnum.class));
        return set;
    }

    @Override
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        Class<?> target = targetType.getType();

        Object[] enumConstants = target.getEnumConstants();
        Class<?> sourceClass = ((SourceEnum) enumConstants[0]).getSource().getClass();
        if(sourceClass == Integer.class && source instanceof String){
            source = Integer.parseInt((String) source);
        }
        SourceEnum sourceEnum;
        for (Object enumConstant : enumConstants) {
            sourceEnum = (SourceEnum) enumConstant;
            if(sourceEnum.getSource().equals(source)){
                return enumConstant;
            }
        }
        return null;
    }
}
